const { BrowserWindow, ipcMain, screen } = require('electron');

let movingInterval = null;

function getWindowByEvent(event) {
  const webContentsId = event.sender.id;
  for (const currentWin of BrowserWindow.getAllWindows()) {
    if (currentWin.webContents.id === webContentsId) {
      return currentWin;
    }
  }
  return null;
}

/**
 * 窗口移动事件
 */
ipcMain.on('window-move-open', (event, canMoving) => {
  let winStartPosition = { x: 0, y: 0 };
  let mouseStartPosition = { x: 0, y: 0 };
  const currentWindow = getWindowByEvent(event);
  const currentWindowSize = currentWindow.getSize();
  if (currentWindow) {
    if (canMoving) {
      // 读取原位置
      const winPosition = currentWindow.getPosition();
      winStartPosition = { x: winPosition[0], y: winPosition[1] };
      // 获取当前鼠标聚焦的窗口
      mouseStartPosition = screen.getCursorScreenPoint();
      // 清除旧的定时器
      if (movingInterval) {
        clearInterval(movingInterval);
      }
      try {
        movingInterval = setInterval(() => {
          // 创建定时器，每10毫秒更新一次窗口位置，保证一致
          // 窗口销毁判断，高频率的更新有可能窗口已销毁，定时器还没结束，此时就会出现执行销毁窗口方法的错误
          if (!currentWindow.isDestroyed()) {
            // 如果窗口失去焦点，则停止移动
            if (!currentWindow.isFocused()) {
              clearInterval(movingInterval);
              movingInterval = null;
            }
            // 实时更新位置
            const cursorPosition = screen.getCursorScreenPoint();
            const x =
              winStartPosition.x + cursorPosition.x - mouseStartPosition.x;
            const y =
              winStartPosition.y + cursorPosition.y - mouseStartPosition.y;
            // 更新位置的同时设置窗口原大小， windows上设置=>显示设置=>文本缩放 不是100%时，窗口会拖拽放大
            currentWindow.setBounds({
              x: x,
              y: y,
              width: currentWindowSize[0],
              height: currentWindowSize[1],
            });
          }
        }, 10);
      } catch (error) {
        console.log(error);
      }
    } else {
      clearInterval(movingInterval);
      movingInterval = null;
    }
  }
});
